<template>
  <div class="purchase" ref="my_purchase">
    <div class="purchase_header">
      <div>
        <p>创建人:{{ detailData.createBy }}</p>
        <p>制单时间：{{ detailData.createTime }}</p>
        <p>采购编码：CG203050679932</p>
        <p>关联订单编码：CG203050679932</p>
      </div>
      <el-button v-if="$route.query.auto" @click="handelClickBack">返回</el-button>
    </div>
    <!--  v-if="useRoutes.query.businessState == 3 ? false : true" -->
    <div class="purchase_supply_information">
      <div class="refuse_becuse">
        <p :style="{ color: detailData.businessState == 2 ? '#FF9900' : '' }">{{ showStatus(detailData.businessState) }}</p>
        <div v-if="detailData.businessState == 3">
          <p>
            拒绝原因：{{
              detailData.refuseType == 1
                ? "原材料上涨"
                : detailData.refuseType == 2
                  ? "商品停产"
                  : detailData.refuseType == 3
                    ? "缺货无法交易"
                    : "其他原因"
            }}
          </p>
          <p>备注：{{ detailData.refuseRemarks }}</p>
        </div>
      </div>
      <div class="purchase_supply_information_serch" v-if="showStatus(detailData.businessState) == '编辑中'">
        <p>供应商</p>
        <div class="purchase_supply_information_serch_select">
          <!-- <div v-if="useRoutes.query.num == 2">{{ detailData.factoryName }}</div> -->
          <div>
            <!-- {{ detailData.factoryId }} -->
            <el-select v-model="detailData.factoryId" @change="handelChangeFactory">
              <el-option v-for="(item, index) in data.gcList" :key="index" :label="item.label" :value="item.value">{{
                item.label
              }}</el-option>
            </el-select>
            <el-button type="primary" :class="detailData.factoryId == null ? 'add_btn' : ''" @click="handelClickAddSp"
              >添加商品</el-button
            >
          </div>
        </div>
      </div>
      <div class="purchase_supply_information_message">
        <div>
          <p>企业名称</p>
          <p>{{ detailData.factoryName }}</p>
        </div>
        <div>
          <p>跟单人员</p>
          <p>{{ detailData.trackerName }}</p>
        </div>
        <div>
          <p>跟单人电话</p>
          <p>{{ detailData.trackerTel }}</p>
        </div>
        <div>
          <p>工厂地址</p>
          <p>{{ detailData.location }}</p>
        </div>
        <div>
          <p>是否支持开票:</p>
          <p v-if="detailData.isSupportBilling == 1">
            {{ `支持开票(专票${detailData.specialTicket}%)(普票${detailData.ordinaryTicket}%)` }}
          </p>
          <p v-else-if="detailData.isSupportBilling === 0">不支持开票</p>
        </div>
      </div>
    </div>
    <div class="purchase_commodity_information">
      <!--创建采购单列表 -->
      <p>商品信息</p>
      <el-table border style="width: 100%" class="jzt-table" :data="detailData.productDetailList">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="name" label="商品信息" width="480">
          <template #default="scope">
            <div class="sp_message">
              <div>
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div>
                <p>{{ scope.row.productAliasName }}</p>
                <!-- <p>
                  {{
                    JSON.parse(scope.row.properties).map(it => {
                      return it.specificationVal + it.specificationName;
                    })
                  }}
                </p> -->
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码:{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.productId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="factoryName" label="供应商信息" /> -->
        <!-- <el-table-column prop="remark" label="备注" /> -->
        <el-table-column prop="remark" label="备注" width="224">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input> -->
            <RemarkEditor v-model="scope.row.remark" />
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="供应单价" />
        <el-table-column prop="commodityNum" label="数量">
          <template #default="scope">
            <el-input-number
              :disabled="detailData.purchaseOrderType == 1"
              style="width: 60px"
              v-model="scope.row.commodityNum"
              :controls="false"
              :min="1"
              @input="handleChangeDiscountRate(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="totalPartNum" label="商品件数" />
        <el-table-column label="折扣率(%)">
          <template #default="scope">
            <el-input-number
              style="width: 60px"
              v-model="scope.row.discountRate"
              :controls="false"
              :min="0"
              @input="handleChangeDiscountRate(scope.row)"
            ></el-input-number>
            <!-- :max="100" -->
          </template>
        </el-table-column>
        <el-table-column label="折扣(元)">
          <template #default="scope">
            {{ scope.row.discountAmount }}
            <!-- <el-input-number
              style="width: 100px"
              v-model="scope.row.discountAmount"
              :min="0"
              :max="scope.row.unitPrice * scope.row.commodityNum"
              :controls="false"
              @input="handelInputZky(scope.row)"
            ></el-input-number> -->
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="采购价格" width="140">
          <template #default="scope">
            <el-input-number
              style="width: 100px"
              :min="0"
              :step="0.1"
              :controls="false"
              v-model="scope.row.actualAmount"
              @input="handelInputActualAmount(scope.row)"
            ></el-input-number>
            <!-- :max="scope.row.unitPrice * scope.row.commodityNum" -->
          </template>
        </el-table-column>
        <el-table-column prop="dealState" label="采购状态">
          <template #default="scope">
            {{
              scope.row.dealState == 1
                ? "待采购"
                : scope.row.dealState == 2
                  ? "待接单 "
                  : scope.row.dealState == 3
                    ? "被拒绝"
                    : scope.row.dealState == 4
                      ? "待发货"
                      : scope.row.dealState == 5
                        ? "部分发货"
                        : scope.row.dealState == 6
                          ? "已发货"
                          : scope.row.dealState == 7
                            ? "待入库"
                            : scope.row.dealState == 8
                              ? "部分入库"
                              : scope.row.dealState == 9
                                ? "已入库"
                                : scope.row.dealState == 10
                                  ? "待出库"
                                  : scope.row.dealState == 11
                                    ? "部分出库"
                                    : scope.row.dealState == 12
                                      ? "已出库"
                                      : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" fixed="right">
          <template #default="scope">
            <el-popconfirm title="确定删除吗?" @confirm="handelClickDelet(scope.row)">
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部表单信息 -->
    <div class="purchase_form">
      <div class="purchase_form-left">
        <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <!-- <el-form-item label="收款账户选择" prop="">
            <el-input placeholder="请选择"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="期望到货日期" prop="">
            <el-date-picker
              v-model="detailData.expectedDeliveryTime"
              type="datetime"
              placeholder="请选择"
              date-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              @change="handleDateTimeChange"
              style="width: 100%"
            />
          </el-form-item> -->
          <el-form-item label="预计生产周期" prop="expectedDeliveryDays">
            <template #label>
              <p>预计生产周期</p>
              <p class="f12" style="line-height: 16px">(请填写天数)</p>
            </template>
            <el-input-number
              class="input-number"
              placeholder="请填写天数"
              v-model="detailData.expectedDeliveryDays"
              :min="0"
              :controls="false"
              style="width: 100%"
            />
            <div style="font-size: 12px; color: #86909c">预计生产周期根据付款节点关联，在对应节点配置生效后启动时间计算！</div>
          </el-form-item>
          <el-form-item label="收货类型" prop="">
            <el-radio-group v-model="detailData.receivingType" class="ml-4">
              <el-radio value="1">收货仓库</el-radio>
              <el-radio value="2" v-if="detailData.purchaseOrderType == 1">直发客户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="其他费用" prop="">
            <!-- <el-input-number
              v-model="detailData.otherFee"
              :step="0.1"
              :precision="2"
              style="width: 100%"
              :controls="false"
              placeholder="请输入"
              @input="handelInputs"
            ></el-input-number> -->
            <el-input v-model="detailData.otherFee" placeholder="" @input="handelInputsOtherFee"></el-input>
          </el-form-item>
          <el-form-item label="优惠金额" prop="">
            <!-- <el-input-number
              v-model="detailData.discountAmount"
              :step="0.1"
              :precision="2"
              style="width: 100%"
              :controls="false"
              placeholder="请输入"
              @input="handelInputs"
            ></el-input-number> -->
            <el-input v-model="detailData.discountAmount" placeholder="" @input="handelInputsDiscountAmount"></el-input>
          </el-form-item>
          <el-form-item label="本次应付金额">
            <template #label> <span style="color: #ff3333">*</span>本次应付金额 </template>
            <!-- <el-input v-model="getData.obj.currentPayableAmount" placeholder="" @input="handelInputsDiscountAmount"></el-input> -->
            <el-input-number
              class="jzt-input-number"
              :min="0"
              :max="
                data.totalPicAll -
                Number(typeof detailData.discountAmount == null ? 0 : detailData.discountAmount) +
                Number(typeof detailData.otherFee === 'undefined' ? 0 : detailData.otherFee)
              "
              :precision="2"
              controls-position="right"
              v-model.trim="detailData.currentPayableAmount"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="订单说明" prop="">
            <!-- <el-input v-model="detailData.remark" type="textarea" @input="handelInputs"></el-input> -->
            <RemarkEditor v-model="detailData.remark" />
          </el-form-item>
          <el-form-item label="附件" prop="">
            <el-upload
              class="upload-demo"
              v-model:file-list="imgFileList"
              ref="uploadImg"
              :show-file-list="true"
              multiple
              :limit="10"
              list-type="text"
              :auto-upload="false"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList);
                }
              "
              :on-preview="handelOnPreview"
            >
              <template #trigger>
                <!-- <el-button :disabled="imgFileList.length >= 10">
                  <el-icon class="f24"><Plus /></el-icon>
                </el-button> -->
                <!-- <el-button style="width: 100%; height: 100%" :disabled="imgFileList.length >= 10">
                  <el-icon class="f24"><Plus /></el-icon>
                </el-button> -->
                <el-button class="update_btn" :disabled="imgFileList.length >= 10">
                  <el-icon class="f24" size="20"><Plus /></el-icon>
                </el-button>
                <p>点击上传</p>
              </template>
              <template #tip>
                <p class="f12 mt10" style="color: #86909c">支持doc/docx/pdf/jpg，最多上传10个。</p>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否开票" prop="isBusinessInvoice">
            <div style="display: flex; justify-content: space-between; width: 100%; background: #f5f7fa; padding: 0 20px">
              <el-radio-group v-model="detailData.isBusinessInvoice">
                <el-radio :value="1">开票</el-radio>
                <el-radio :value="0">不开票</el-radio>
              </el-radio-group>

              <div
                v-if="detailData.isSupportBilling == 0 && detailData.isBusinessInvoice === 1"
                style="color: #ff3333; font-size: 12px"
              >
                当前供应商不支持开票，请致电沟通后在提交采购单！
              </div>
            </div>
            <div class="warehouse_content" v-if="detailData.isBusinessInvoice === 1">
              <el-select v-model="detailData.invoiceType" placeholder="请选择开票类型" @change="invoiceTypeChange">
                <el-option label="专票" :value="1" />
                <el-option label="普票" :value="2" />
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="purchase_form-right">
        <div class="purchase_form-right-top">
          <div class="header" v-if="detailData.receivingType == 1">
            <p>收货仓库</p>
            <el-select v-model="detailData.receivingWarehouseId" @change="handelChangePutAway">
              <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
          <p class="title">收货信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ detailData.receivingName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ detailData.receivingMobile }}</p>
          </div>
          <div>
            <p>
              收货地址:
              <span v-if="detailData.receivingType == 2">
                <el-icon
                  v-if="showStatus(detailData.businessState) !== '编辑中'"
                  style="vertical-align: middle"
                  size="20"
                  color="#007DFF"
                  @click="handelClickEditAdess"
                >
                  <Edit />
                </el-icon>
              </span>
            </p>
            <!-- <p v-if="detailData.receivingType == 1">{{ detailData.receivingAreaDetail }}{{ detailData.receivingAddress }}</p> -->
            <p>{{ detailData.receivingAreaDetail + detailData.receivingAddress }}</p>
          </div>
        </div>
        <!-- v-if="detailData.receivingType == 2" -->
        <div class="purchase_form-right-top" v-if="detailData.purchaseOrderType == 1">
          <p class="title">客户信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ detailData.customerName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ detailData.customerMobileCode }}</p>
          </div>
          <div>
            <p>收货地址:</p>
            <p>{{ detailData.customerAddress }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="botton_btn" :style="{ width: footerWidth + 'px' }">
      <div class="left">
        <div class="mb16">
          <p>
            优惠金额：¥<span>{{ detailData.discountAmount }}</span>
          </p>
          <p>
            其他费用：¥<span>{{ detailData.otherFee }}</span>
          </p>
          <p v-if="detailData.isBusinessInvoice == 1">
            税额：¥<span>{{ detailData.feeAmount }}</span>
          </p>
        </div>
        <div>
          <p>
            商品总价：¥<span>{{ data.totalPicAlly }}</span>
          </p>
          <p>
            未付金额：<span>¥{{ detailData.remainTotalAmount }}</span>
          </p>
          <p>
            实付金额：<span>¥{{ detailData.actualTotalAmount }}</span>
          </p>
          <p>
            应付金额：
            <span>{{
              data.totalPicAll -
              Number(typeof detailData.discountAmount == null ? 0 : detailData.discountAmount) +
              Number(typeof detailData.otherFee === "undefined" ? 0 : detailData.otherFee)
            }}</span>
          </p>
        </div>
      </div>
      <div class="right">
        <!-- 拒绝采购单 -->
        <div v-if="detailData.businessState == 3">
          <el-button type="" @click="handelClicClose(1)">关闭</el-button>
          <el-button type="primary" @click="handelClickCreatePurchase()"> 重新提交 </el-button>
        </div>
        <!-- 待接单 -->
        <div v-if="detailData.businessState == 2">
          <el-button type="" @click="handelClicClose(2)">取消采购</el-button>
          <el-button type="primary" @click="handelClickCreatePurchaseSubmit()"> 提交采购单 </el-button>
        </div>
        <!-- 编辑中 -->
        <div v-if="detailData.businessState == 1">
          <el-button type="" @click="handelClicClose(2)">关闭采购订单</el-button>
          <el-button type="primary" plain @click="handelClicksaveOder()"> 保存 </el-button>
          <el-button type="primary" @click="handelClickCreatePurchaseSubmit()"> 创建采购单 </el-button>
        </div>
      </div>
    </div>
    <!-- 修改订单地址 -->
    <dialog-View :isShow="data.isShowAdess" :title="'修改地址'" :width="'30%'">
      <form-View
        :formList="data.formListOrderAdess"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        @update="handelUpdateAdess"
        @back="handelBackAdess"
      ></form-View>
    </dialog-View>
    <!-- 切换供应商提示 -->
    <dialog-View :isShow="data.switchingPrompt" :title="''" :width="'30%'">
      <div>
        <el-button type="">取消</el-button>
        <el-button type="primary">确定</el-button>
      </div>
    </dialog-View>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, watch, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  getFactoryInfo,
  purchaseOrderId,
  getlistByTenantId,
  // getSuppliers,
  getTempProductSkuList,
  createSubmit,
  // delTempProductSku,
  savePurchaseOrder,
  getProvideList,
  // closeOder
  resubmit,
  closPurchaseOrderId
} from "@/apis/procure/index";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import china from "@/utils/china.json";
import dayjs from "dayjs";
const chinas = ref(china);
import { shoppingList } from "@/store/index";
import { imgsUpload } from "@/apis/products/specifications";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
const shoppingLists = shoppingList();
import { ElMessage, ElMessageBox } from "element-plus";
import { roundDecimal, mathRound } from "@/utils/summation";
// 组件导入
import dialogView from "./components/dialogView.vue";
import formView from "./components/formView.vue";
import RemarkEditor from "@/components/RemarkEditor";
// 获取商品的数据
// 组件导入
// import dialogView from '@/components/dialogView/index.vue'
const useRout = useRouter();
const useRoutes = useRoute();
const ruleFormRef = ref();
const ruleForm = ref({});
// 底部栏的动态宽度
const footerWidth = ref(0);
// 获取dom
const my_purchase = ref();
const rules = ref({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  ]
});
const forms = ref({});
const data = reactive({
  // 显示修改地址弹框
  isShowAdess: false,
  // 修改地址------------
  formListOrderAdess: [
    { label: "收货人", model: "receivingName", type: "input" },
    { label: "手机", model: "receivingMobile", type: "input" },
    { label: "收货地址", model: "receivingAddress", type: "cascader", options: chinas },
    { label: "详细地址", model: "receivingAreaDetail", type: "input" }
  ],
  // 修改地址规则
  rulesOrderAdess: {
    receivingName: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 1, max: 200, message: "请输入名称", trigger: "blur" }
    ],
    receivingMobile: [
      { required: true, message: "请输入电话", trigger: "blur" },
      { min: 1, max: 200, message: "请输入电话", trigger: "blur" }
    ],
    receivingAddress: [
      {
        required: true,
        message: "请选择地址",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            return callback(new Error("请选择一个地址"));
          }
          return callback();
        }
      }
    ],
    receivingAreaDetail: [
      { required: true, message: "请输入详细地址", trigger: "blur" },
      { min: 1, max: 300, message: "请输入详细地址", trigger: "blur" }
    ]
  },
  totalPicAll: 0,
  totalPicAlly: 0,
  // 创建采购单-------
  gcList: [], //供应商列表数据
  informationObj: {},
  // 创建采购单------end
  orderId: "",
  num: 1, //1代表普通采购单，2代表定时采购单
  totalPic: 0,
  // 清除定时
  isShowClearTime: false,
  // 清除定时-------end
  code: "", //编辑添加商品保存时间挫
  switchingPrompt: false,
  supplierID: "" //切换供应商保存的数据
});
// 下载
const handelOnPreview = v => {
  const link = document.createElement("a");
  link.href = v.fileUrl;
  link.click();
};
// 上传
// 上传
// const imgIsReady = ref(true);
const FileList = ref([]); //商品图片list
// const uploadImg = ref();
// import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
// const ossStore = useMultipartOssStore();
// import {
//   getFolder
//   // _debounce //防抖，多次频繁触发时，只执行最后一次
// } from "@/utils/index";
// import { imgsUpload } from "@/apis/products/specifications";
const uploadImg = ref();
const imgFileList = ref([]); //编辑时商品图片list
const imgIsReady = ref(true);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img-word") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img-word" ? _fileList : [file]);
  if (!flag) {
    if (type === "img-word") {
      ElMessage({
        message: "支持扩展名：doc/docx/pdf/jpg",
        type: "error",
        offset: 60
      });
      const errorFile = _fileList.filter(
        item =>
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf"
          )
      );
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    return;
  }
  if (type === "img-word") {
    FileList.value = fileList;
    imgIsReady.value = false;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
    imgIsReady.value = true;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "img-word") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
// 修改折扣率
const picData = ref(0);
const handleChangeDiscountRate = item => {
  console.log(item, "2222");
  // return
  setTimeout(() => {
    copyTabelList.value.productDetailList.map(it => {
      if (it.collectId === item.collectId) {
        picData.value = it.actualAmount;
      }
    });
    let total = Number(item.commodityNum) * Number(item.unitPrice) * (Number(item.discountRate) / 100); //实际价格
    let zkTotal =
      Number(item.commodityNum) * Number(item.unitPrice) -
      Number(item.commodityNum) * Number(item.unitPrice) * (Number(item.discountRate) / 100); //则扣总价
    console.log(total, zkTotal, Number(item.discountRate) / 100);
    const n = roundDecimal(zkTotal / Number(item.commodityNum), 2);
    item.actualAmount = roundDecimal(total, 2);
    item.discountAmount = n;
  });
};
// 输入采购价
const handelInputActualAmount = item => {
  setTimeout(() => {
    item.discountRate = mathRound((item.actualAmount / item.commodityNum / item.unitPrice) * 100);
    let zkTotal =
      Number(item.commodityNum) * Number(item.unitPrice) -
      Number(item.commodityNum) * Number(item.unitPrice) * (Number(item.discountRate) / 100); //则扣总价
    const ddiscountAmount = roundDecimal(zkTotal / Number(item.commodityNum), 2);
    item.discountAmount = ddiscountAmount;
    // getpayTotal();
  }, 0);
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const attachmentFileUrls = ref([]); //上传的文件的最后结果
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      attachmentFileUrls.value.push(res.fileUrl.split("?")[0]);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      } else {
        item["video"] = res.fileUrl.split("?")[0];
        // console.log("视频===", videoList.value);
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  await new Promise(resolve => {
    audioElement.addEventListener("loadedmetadata", () => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};
// 显示状态
const showStatus = n => {
  console.log(n, "状态");
  switch (n) {
    case 0:
      return "定时中";
    case 1:
      return "编辑中";
    case 2:
      return "待接单";
    case 3:
      return "已拒绝订单";
    case 4:
      return "待发货";
    case 5:
      return "部分待入库";
    case 6:
      return "待入库";
    case 7:
      return "部分入库";
    case 8:
      return "已入库";
    case 9:
      return "已关闭";
    default:
      "";
  }
};
// 时间转换
const handleDateTimeChange = value => {
  detailData.value.expectedDeliveryTime = value;
  detailData.value.expectedDeliveryTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
};
//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
// 关闭订单
const handelClicClose = n => {
  closPurchaseOrderId(useRoutes.query.purchaseOrderId).then(res => {
    console.log(res);
    if (res.code === 200) {
      ElMessage({
        type: "success",
        message: n == 1 ? "关闭采购单成功" : n == 2 ? "取消采购单成功" : ""
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 1000);
    }
  });
};
// 返回
const handelClickBack = () => {
  useRout.push({
    path: "/procure/purchase-order"
  });
};
// 新创建采购单----------
const getProvideLists = async () => {
  const resalt = await getProvideList({ status: 1 }, 1000, 1000);
  let arr = [];
  resalt.data.list.map(it => {
    arr.push({ label: it.factoryName, value: it.factoryId });
  });
  data.gcList = arr;
};
const handelClickAddSp = () => {
  if (detailData.value.receivingWarehouseId == "") return;
  if (data.code === "") {
    data.code = Date.now();
  }
  useRout.push({
    path: "/procure/purchase-order/merchant-add",
    query: {
      factoryId: detailData.value.factoryId,
      code: data.code,
      purchaseOrderId: useRoutes.query.purchaseOrderId,
      edit: true
    }
  });
};
// 获取商品信息列表
const getTempProductSkuLists = () => {
  // return
  getTempProductSkuList({ code: data.code, businessId: JSON.parse(localStorage.getItem("userinfo")).tenantId })
    .then(res => {
      // 添加字段  则扣金额，则扣率
      res.data.map(it => {
        detailData.value.productDetailList.push({
          actualAmount: it.factoryRealPrice == null ? 0 : it.factoryRealPrice,
          businessSkuId: it.businessSkuId,
          collectId: it.collectId,
          commodityNum: 1,
          dealState: 1,
          discountAmount: 0,
          discountRate: 100,
          // goodsPartNum: 2,
          mainPicUrl: it.mainPicUrl,
          partNum: it.partNum == null ? 1 : it.partNum,
          productAliasName: it.productAliasName,
          productId: it.productId,
          productUnit: it.productUnit,
          properties: it.skuProperties,
          skuCode: it.skuCode,
          unitPrice: it.factoryPrice == null ? 0 : it.factoryPrice,
          updateBy: "工厂fc",
          updateId: "1805501818356166656"
        });
      });
      // 赋值给原来初始拷贝的数据
      copyTabelList.value = detailData.value;
    })
    .catch(err => {
      console.log(err);
    });
};
const handelChangeFactory = v => {
  // 保存缓存
  console.log(detailData.value.factoryId, "-------", v, data.supplierID);

  // shoppingLists.editObject = forms.value;
  // data.switchingPrompt=true
  ElMessageBox.confirm("更换供应商将清空商品信息，确认更换？", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      getFactoryInfo(v).then(res => {
        const { factoryName, trackerName, trackerTel, area } = res.data;
        if (res.code === 200) {
          detailData.value.factoryName = factoryName;
          detailData.value.trackerName = trackerName;
          detailData.value.trackerTel = trackerTel;
          detailData.value.location = area;
          ElMessage({
            type: "success",
            message: "更换供应商成功"
          });
        }
        // 保存供应商id
        data.supplierID = v;
        detailData.value.productDetailList = [];
        // 保存缓存
        // 切换的时候重新生成code码
        data.code = Date.now();
        shoppingLists.editObject = detailData.value;

        // 是否开票
        detailData.value.invoiceType = null;
        detailData.value.isSupportBilling = res.data.isSupportBilling;
        detailData.value.isBusinessInvoice = res.data.isSupportBilling;
        detailData.value.specialTicket = res.data.specialTicket;
        detailData.value.ordinaryTicket = res.data.ordinaryTicket;
      });
    })
    .catch(() => {
      console.log("取消更换");
      // 取消时还原原来的供应商
      detailData.value.factoryId = data.supplierID;
    });
  return;
};
const warehouseList = ref([]);
const warehouseArry = ref([]);
const warehouseObj = ref({}); //获取最后的收货数据
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    warehouseArry.value = res.data;
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    warehouseList.value = arr;
  });
};
// 修改地址---------------
const handelClickEditAdess = () => {
  data.isShowAdess = true;
};
const handelUpdateAdess = (item, address) => {
  console.log(item);
  detailData.value.receivingName = item.receivingName;
  detailData.value.receivingMobile = item.receivingMobile;
  detailData.value.receivingAreaDetail = address + item.receivingAreaDetail;
  detailData.value.receivingAreaIds = item.receivingAddress.join(",");
  data.isShowAdess = false;
};
const handelBackAdess = () => {
  data.isShowAdess = false;
};
const handelChangePutAway = v => {
  warehouseArry.value.map(it => {
    if (v === it.warehouseId) {
      // warehouseObj.value = it;
      detailData.value.receivingName = it.warehouseName;
      detailData.value.receivingMobile = it.managePhoneNo;
      detailData.value.receivingAreaDetail = it.provinceName + it.cityName + it.districtName;
      detailData.value.receivingAddress = it.address;
    }
  });
};
// 新建采购单添加到缓存的数据
const copyTabelList = ref();

// 删除
const handelClickDelet = item => {
  if (detailData.value.productDetailList.length <= 1) {
    ElMessage({
      type: "warning",
      message: "商品只有一项不能删除"
    });
    return;
  }
  let idToRemove = item.businessSkuId;
  detailData.value.productDetailList = detailData.value.productDetailList.filter(item => item.businessSkuId !== idToRemove);
  ElMessage({
    message: "删除成功",
    type: "success"
  });
};
// 发起采购订单
const handelClickCreatePurchase = () => {
  let copys = JSON.stringify(detailData.value);
  let copyss = JSON.parse(copys);

  const arrFiles = [];
  // 处理上传文件
  imgFileList.value.map(it => {
    arrFiles.push(it.video);
  });
  copyss.purchaseOrderDetails = copyss.productDetailList;
  let parms = {
    ...copyss,
    attachmentFileUrls: arrFiles.join(",")
  };
  // console.log("发起采购-参数===", parms, imgFileList.value);
  // return;
  resubmit(parms)
    .then(res => {
      console.log(res);
      ElMessage({
        type: "success",
        message: "提交成功"
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 2000);
    })
    .catch(err => {
      console.log(err);
    });
};
// 待接单采购单
const handelClickCreatePurchaseSubmit = () => {
  // return
  let copys = JSON.stringify(detailData.value);
  let copyss = JSON.parse(copys);
  copyss.purchaseOrderDetails = copyss.productDetailList;
  copyss.receivingAddress = copyss.receivingAreaDetail;
  let filArr = [];
  console.log();

  imgFileList.value.map(it => {
    filArr.push(it.fileUrl == undefined ? it.video : it.fileUrl);
  });
  console.log(filArr, "0000");
  // return
  copyss.attachmentFileUrls = filArr.join(",");
  // copys.otherFee=Number(copyss.otherFee)
  // console.log(copyss,'----------');
  // delete copyss.autoPurchaseTime
  // return
  let parms = {
    ...copyss
  };
  const currentPayableAmount = detailData.value.currentPayableAmount;
  if (
    JSON.stringify(currentPayableAmount) === "" ||
    JSON.stringify(currentPayableAmount) === "null" ||
    JSON.stringify(currentPayableAmount) === undefined
  ) {
    return ElMessage({
      message: "请输入本次应付金额",
      type: "error"
    });
  }
  createSubmit(parms)
    .then(res => {
      console.log(res);
      ElMessage({
        type: "success",
        message: "提交成功"
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 2000);
    })
    .catch(err => {
      console.log(err);
    });
};
// 提交采购单
const handelClicksaveOder = () => {
  let copys = JSON.stringify(detailData.value);
  let copyss = JSON.parse(copys);
  copyss.purchaseOrderDetails = copyss.productDetailList;
  copyss.receivingAddress = copyss.receivingAreaDetail;
  let filArr = [];
  imgFileList.value.map(it => {
    filArr.push(it.fileUrl == undefined ? it.video : it.fileUrl);
  });
  console.log(filArr, "0000");
  // return
  copyss.attachmentFileUrls = filArr.join(",");
  let parms = {
    ...copyss
  };
  savePurchaseOrder(parms)
    .then(res => {
      console.log(res);
      ElMessage({
        type: "success",
        message: "保存成功"
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 2000);
    })
    .catch(err => {
      console.log(err);
    });
};
const handelInputsOtherFee = () => {
  detailData.value.otherFee = detailData.value.otherFee.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
const handelInputsDiscountAmount = () => {
  detailData.value.discountAmount = detailData.value.discountAmount.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
// 新创建采购单----------end
// 查询详情---------
const detailData = ref({});
const getDetails = () => {
  purchaseOrderId(useRoutes.query.purchaseOrderId).then(res => {
    console.log(res, "-----------333");
    res.data.receivingType = res.data.receivingType.toString();
    detailData.value = res.data;
    // 回显附件
    const imgFileListArr = res.data.attachmentFileUrls;
    const newFiles = imgFileListArr.length > 0 ? imgFileListArr.split(",") : [];
    const reslatFileArr = [];
    newFiles.map(it => {
      reslatFileArr.push({
        url: it,
        fileUrl: it,
        name: decodeURI(it).split("/")[decodeURI(it).split("/").length - 1]
      });
    });
    imgFileList.value = reslatFileArr;
    // 编辑时回显工产id
    forms.value.factoryId = res.data.factoryId;
    // 拷贝一份原始数据
    let obj = JSON.stringify(res.data);
    let obj1 = JSON.parse(obj);
    copyTabelList.value = obj1;
    shoppingLists.editOriginData = obj1;
    // 保存供应商id
    data.supplierID = res.data.factoryId;
  });
};

// 查询详情---------end
onMounted(() => {
  getProvideLists();
  getlistByTenantIds();
  // 判断是否有code
  if (data.code === "") {
    data.code = useRoutes.query.code == undefined ? Date.now() : useRoutes.query.code;
    getTempProductSkuLists();
  }
  //  走详情页面

  // 获取添加的商品
  if (useRoutes.query.edit) {
    // 如果是直接点击添加商品则清空缓存列表数据
    shoppingLists.editOriginData.productDetailList = [];
    console.log(shoppingLists.editOriginData, "shoppingLists.editObject");
    detailData.value = shoppingLists.editOriginData;
  } else {
    getDetails();
  }
  // 初始化地址数据
  chinas.value.map(item => {
    // 第一层
    item.label = item.name;
    item.value = item.cityCode;
    // eslint-disable-next-line no-prototype-builtins
    if (item.hasOwnProperty("children")) {
      console.log("第二层");
      // 第二层
      item.children.map(citem => {
        citem.label = citem.name;
        citem.value = citem.cityCode;
        // eslint-disable-next-line no-prototype-builtins
        if (citem.hasOwnProperty("children")) {
          // 第三层
          citem.children.map(ccitem => {
            ccitem.label = ccitem.name;
            ccitem.value = ccitem.cityCode;
          });
        }
      });
    }
  });
  // 获取dom元素给底部操作栏设置动态宽度
  if (my_purchase.value) {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        footerWidth.value = entry.contentRect.width;
      }
    });

    resizeObserver.observe(my_purchase.value);
    // 组件卸载时取消监听
    onUnmounted(() => {
      resizeObserver.disconnect();
    });
  }
});
// 监听数据则到总价
watch(
  () => detailData.value.productDetailList,
  list => {
    console.log(list, "----------------------监听数据1111");
    const realt = list?.reduce((accumulator, currentObject) => {
      return accumulator + Number(currentObject.actualAmount);
    }, 0);
    console.log(realt);
    data.totalPicAll = realt;
    // 商品总价
    const realt1 = list?.reduce((accumulator, currentObject) => {
      return accumulator + Number(currentObject.unitPrice * currentObject.commodityNum);
    }, 0);
    data.totalPicAlly = realt1;

    invoiceTypeChange();
  },
  {
    deep: true
    // immediate: true
  }
);
watch(
  () => detailData.value.receivingType,
  v => {
    if (v == 2) {
      const { customerReceivingAreaDetail, customerReceivingAddress, customerMobileCode, customerName } = detailData.value;
      detailData.value.receivingAreaDetail = customerReceivingAreaDetail;
      detailData.value.receivingMobile = customerMobileCode;
      detailData.value.receivingName = customerName;
      detailData.value.receivingAddress = customerReceivingAddress;
    } else {
      detailData.value.receivingAreaDetail = shoppingLists.editOriginData.receivingAreaDetail;
      detailData.value.receivingMobile = shoppingLists.editOriginData.receivingMobile;
      detailData.value.receivingName = shoppingLists.editOriginData.receivingName;
      detailData.value.receivingAddress = shoppingLists.editOriginData.receivingAddress;
    }
  },
  { deep: true }
);

// 开票类型变化-算开票金额和税额
const invoiceTypeChange = () => {
  let num = 0;
  // 支持开票-取开票的税率，不支持取0
  if (detailData.value.isSupportBilling == 1) {
    if (detailData.value.invoiceType == 1) {
      num = Number(detailData.value.specialTicket || 0);
    } else if (detailData.value.invoiceType == 2) {
      num = Number(detailData.value.ordinaryTicket || 0);
    }
  }
  let commodityPrice =
    data.totalPicAll -
    Number(typeof detailData.value.discountAmount == null ? 0 : detailData.value.discountAmount) +
    Number(typeof detailData.value.otherFee === "undefined" ? 0 : detailData.value.otherFee);
  // 小数点2位 *1000 避免长度失真
  detailData.value.feeAmount = (((commodityPrice * 1000) / 100) * num * 1000) / 1000000;
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
